package com.base.controller;

import com.base.comm.CommContent;
import com.base.comm.CommUrls;
import com.base.helper.VosHelper;
import com.base.helper.WebHelper;
import com.base.po.param.VosModelList;
import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class content_xiugaiyonghu {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private SubscribersService subscribersService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private PayinfoesService payinfoesService;
	@Autowired
	private RewardsService rewardsService;
	@Autowired
	private WithdrawalsService withdrawalsService;

	// 账户信息
	@RequestMapping("/content_xiugaiyonghu")
	public ModelAndView index(HttpServletRequest request, @RequestParam(value = "id", required = true) String id)
			throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		Subscribers users = subscribersService.selectByPrimaryKey(id);
		if (users == null || users.getId() == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}

		float ig = 0f;
		List<Rewards> igList = rewardsService.selectByPhase(adminUserId, users.getId());
		if (igList != null && igList.size() > 0){
			Rewards rewards = igList.get(0);
			ig = rewards.getIntegral().floatValue();
		}
		float igw = 0f;
		List<Rewards> igwList = rewardsService.selectByWithdraw(adminUserId, users.getId());
		if (igwList != null && igwList.size() > 0){
			Rewards rewards = igwList.get(0);
			igw = rewards.getIntegral().floatValue();
		}
		float integral = rewardsService.countByIntegral(users.getParentid(), users.getId())
				+ rewardsService.countByBonus(users.getParentid(), users.getId())
				+ rewardsService.countByExtra(users.getParentid(), users.getId())
				+ rewardsService.countBySelfShop(users.getParentid(), users.getId())
				+ rewardsService.countByRefund(users.getParentid(), users.getId())
				- ig;
		users.setIgrewardAll(integral);
		users.setWithdrawalsAll((withdrawalsService.countByAlready(users.getId(), 2, 1)/0.92f) - igw);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endtime = dateFormat.format(users.getEndtime());

		// TODO 代理商信息
		Users pUsers = usersService.selectByPrimaryKey(users.getParentid());
		// TODO 上级商家信息
		Users sUsers = usersService.selectByPrimaryKey(users.getShopid());
		request.setAttribute("id", id);
		request.setAttribute("password", PasswordUtils.decodePWD(users.getPassword()));
		request.setAttribute("endtime", endtime);
		request.setAttribute("datastatus", users.getDatastatus());
		request.setAttribute("mobile", users.getMobile());
		request.setAttribute("shopBalance", users.getShopBalance());
		request.setAttribute("pic", users.getPic());
		request.setAttribute("parentid", pUsers.getUsername());
		request.setAttribute("shopid", sUsers.getUsername());
		request.setAttribute("igreward", users.getIgreward() == null ? 0 : users.getIgreward());
		request.setAttribute("shareper", users.getShareper() == null || users.getShareper() == "" ? "" : subscribersService.selectByPrimaryKey(users.getShareper()).getMobile());
		request.setAttribute("achievement1", users.getAchievement1());
		request.setAttribute("achievement2", users.getAchievement2());
		request.setAttribute("achievement3", users.getAchievement3());
		request.setAttribute("iswithdraw", users.getIswithdraw());
		request.setAttribute("isbonus", users.getIsbonus());
		request.setAttribute("isperformance", users.getIsperformance());
		request.setAttribute("cbonus1level", users.getCbonus1level());
		request.setAttribute("cbonus2level", users.getCbonus2level());
		request.setAttribute("cbonus3level", users.getCbonus3level());
		request.setAttribute("isallprivilege", users.getIsallprivilege());
		request.setAttribute("allteamreratio", users.getAllteamreratio());
		request.setAttribute("isprivilege", users.getIsprivilege());
		request.setAttribute("teamreratio", users.getTeamreratio());
		request.setAttribute("adminUsergrade", adminUsergrade);
		request.setAttribute("adminUserId", adminUserId);
		request.setAttribute("member", users.getMember());
		request.setAttribute("ismember", users.getIsmember());

		request.setAttribute("igrewardAll", users.getIgrewardAll());
		request.setAttribute("withdrawalsAll", users.getWithdrawalsAll());

		BigDecimal shareNum = payinfoesService.selectAllPerformance(users.getId(), 1).subtract(new BigDecimal(users.getAchievement1()));
		BigDecimal shareNum2 = payinfoesService.selectAllPerformance(users.getId(), 2).subtract(new BigDecimal(users.getAchievement2()));
		BigDecimal shareNum3 = payinfoesService.selectAllPerformance(users.getId(), 3).subtract(new BigDecimal(users.getAchievement3()));
		request.setAttribute("achlevel1Num", shareNum);
		request.setAttribute("achlevel2Num", shareNum2);
		request.setAttribute("achlevel3Num", shareNum3);

		Users parent = usersService.selectByPrimaryKey(users.getParentid());
		Users shop = usersService.selectByPrimaryKey(users.getShopid());

		if (parent != null && parent.getUsername() != null) {
			users.setParentid(parent.getUsername());

		} else {
			users.setParentid("未知");
		}

		if (shop != null && shop.getUsername() != null) {
			users.setShopid(shop.getUsername());
		} else {
			users.setShopid("未知");
		}
		request.setAttribute("parentid", users.getParentid());
		request.setAttribute("shopid", users.getShopid());
		// request.setAttribute("freeroute", freeroute);

		if (request.getSession().getAttribute("adminUserId") == null) {
			modelAndView.setViewName("jsp/login");
		} else {
			modelAndView.setViewName("jsp/content_xiugaiyonghu");
		}
		return modelAndView;
	}

	// 账户信息
	@RequestMapping("/content_xiugaistyonghu")
	public ModelAndView content_xiugaistyonghu(HttpServletRequest request, @RequestParam(value = "id", required = true) String id)
			throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		Subscribers users = subscribersService.selectByPrimaryKey(id);
		if (users == null || users.getId() == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endtime = dateFormat.format(users.getEndtime());

		users.setIgrewardAll(rewardsService.countByIntegral(adminUserId, users.getId())
				+ rewardsService.countByBonus(adminUserId, users.getId())
				+ rewardsService.countByExtra(adminUserId, users.getId())
				- (withdrawalsService.countByAlready(users.getId(), 2, 1)/0.92f));
		users.setWithdrawalsAll(withdrawalsService.countByAlready(users.getId(), 2, 1)/0.92f);

		// TODO 代理商信息
		Users pUsers = usersService.selectByPrimaryKey(users.getParentid());
		// TODO 上级商家信息
		Users sUsers = usersService.selectByPrimaryKey(users.getShopid());
		request.setAttribute("id", id);
		request.setAttribute("password", PasswordUtils.decodePWD(users.getPassword()));
		request.setAttribute("endtime", endtime);
		request.setAttribute("datastatus", users.getDatastatus());
		request.setAttribute("mobile", users.getMobile());
		request.setAttribute("shopBalance", users.getShopBalance());
		request.setAttribute("pic", users.getPic());
		request.setAttribute("parentid", pUsers.getUsername());
		request.setAttribute("shopid", sUsers.getUsername());
		request.setAttribute("igreward", users.getIgreward() == null ? 0 : users.getIgreward());
		request.setAttribute("shareper", users.getShareper() == null || users.getShareper() == "" ? "" : subscribersService.selectByPrimaryKey(users.getShareper()).getMobile());
		request.setAttribute("achievement1", users.getAchievement1());
		request.setAttribute("achievement2", users.getAchievement2());
		request.setAttribute("achievement3", users.getAchievement3());
		request.setAttribute("iswithdraw", users.getIswithdraw());
		request.setAttribute("isbonus", users.getIsbonus());
		request.setAttribute("isperformance", users.getIsperformance());
		request.setAttribute("cbonus1level", users.getCbonus1level());
		request.setAttribute("cbonus2level", users.getCbonus2level());
		request.setAttribute("cbonus3level", users.getCbonus3level());
		request.setAttribute("isallprivilege", users.getIsallprivilege());
		request.setAttribute("allteamreratio", users.getAllteamreratio());
		request.setAttribute("isprivilege", users.getIsprivilege());
		request.setAttribute("teamreratio", users.getTeamreratio());
		request.setAttribute("adminUsergrade", adminUsergrade);
		request.setAttribute("adminUserId", adminUserId);
		request.setAttribute("igrewardAll", users.getIgrewardAll());
		request.setAttribute("withdrawalsAll", users.getWithdrawalsAll());

		Users parent = usersService.selectByPrimaryKey(users.getParentid());
		Users shop = usersService.selectByPrimaryKey(users.getShopid());

		if (parent != null && parent.getUsername() != null) 	{
			users.setParentid(parent.getUsername());

		} else {
			users.setParentid("未知");
		}

		if (shop != null && shop.getUsername() != null) {
			users.setShopid(shop.getUsername());
		} else {
			users.setShopid("未知");
		}
		request.setAttribute("parentid", users.getParentid());
		request.setAttribute("shopid", users.getShopid());
		// request.setAttribute("freeroute", freeroute);

		if (request.getSession().getAttribute("adminUserId") == null) {
			modelAndView.setViewName("jsp/login");
		} else {
			modelAndView.setViewName("jsp/content_xiugaistyonghu");
		}
		return modelAndView;
	}

	@RequestMapping("/content_xiugaishangjiayonghu")
	public ModelAndView indexShop(HttpServletRequest request, @RequestParam(value = "id", required = true) String id,
								  String pid)throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		Subscribers users = subscribersService.selectByPrimaryKey(id);
		if (users == null || users.getId() == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		System.out.println(users.toString());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endtime = dateFormat.format(users.getEndtime());

		// TODO 代理商信息
		Users pUsers = usersService.selectByPrimaryKey(users.getParentid());
		// TODO 上级商家信息
		Users sUsers = usersService.selectByPrimaryKey(users.getShopid());
		request.setAttribute("id", id);
		request.setAttribute("password", PasswordUtils.decodePWD(users.getPassword()));
		request.setAttribute("endtime", endtime);
		request.setAttribute("datastatus", users.getDatastatus());
		request.setAttribute("mobile", users.getMobile());
		request.setAttribute("shopBalance", users.getShopBalance());
		request.setAttribute("pic", users.getPic());
		request.setAttribute("parentid", pUsers.getUsername());
		request.setAttribute("shopid", sUsers.getUsername());
		request.setAttribute("igreward", users.getIgreward() == null ? 0 : users.getIgreward());
		request.setAttribute("shareper", users.getShareper() == null ? null : subscribersService.selectByPrimaryKey(users.getShareper()).getMobile());
		request.setAttribute("achievement1", users.getAchievement1());
		request.setAttribute("achievement2", users.getAchievement2());
		request.setAttribute("achievement3", users.getAchievement3());
		request.setAttribute("iswithdraw", users.getIswithdraw());
		request.setAttribute("isbonus", users.getIsbonus());
		request.setAttribute("isperformance", users.getIsperformance());
		request.setAttribute("cbonus1level", users.getCbonus1level());
		request.setAttribute("cbonus2level", users.getCbonus2level());
		request.setAttribute("cbonus3level", users.getCbonus3level());
		request.setAttribute("isallprivilege", users.getIsallprivilege());
		request.setAttribute("allteamreratio", users.getAllteamreratio());
		request.setAttribute("isprivilege", users.getIsprivilege());
		request.setAttribute("teamreratio", users.getTeamreratio());
		request.setAttribute("adminUsergrade", adminUsergrade);
		request.setAttribute("adminUserId", adminUserId);

		Users parent = usersService.selectByPrimaryKey(users.getParentid());
		Users shop = usersService.selectByPrimaryKey(users.getShopid());

		if (parent != null && parent.getUsername() != null) {
			users.setParentid(parent.getUsername());

		} else {
			users.setParentid("未知");
		}

		if (shop != null && shop.getUsername() != null) {
			users.setShopid(shop.getUsername());
		} else {
			users.setShopid("未知");
		}
		request.setAttribute("parentid", users.getParentid());
		request.setAttribute("shopid", users.getShopid());
		request.setAttribute("pid", pid);
		// request.setAttribute("freeroute", freeroute);

		if (request.getSession().getAttribute("adminUserId") == null) {
			modelAndView.setViewName("jsp/login");
		} else {
			modelAndView.setViewName("jsp/content_xiugaishangjiayonghu");
		}
		return modelAndView;
	}

	String SUCCESS = "success";

	// 更改商户信息
	@RequestMapping(value = "/updateSubscribers", method = RequestMethod.POST)
	public void updateSubscribersUser(HttpServletRequest request, HttpServletResponse response,
									  @RequestParam(value = "id", required = true) String id, String password, Date createtime, Date logintime,
									  String loginip, Integer role, Boolean datastatus, String mobile, String parentid, String pic,
									  String endtime, Integer type, String shopid, String appstore, Float integral, String aliaccount,
									  Boolean alipay, Integer shopBalance, String shopEnddate, String birthday, String gender, String email,
									  String address, String username, Boolean isyear, Boolean ismonth, Boolean isquarter, Integer money,
									  String shareper, Float igreward, Integer achievement1, Integer achievement2, Integer achievement3,
									  Byte iswithdraw, Byte isbonus, Byte isperformance, Integer cbonus1level, Integer cbonus2level, Integer cbonus3level,
									  Integer isallprivilege, BigDecimal allteamreratio, Integer isprivilege, BigDecimal teamreratio, Integer isyearcard,
									  Integer zxRewards, Integer isbuycard, Float igwithdrawals, Integer fans, String telCheck, Boolean isWxUntying,
									  Integer member, Integer ismember)throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date newEndtime = null;
		if (endtime != null && !endtime.equals("")) {
			newEndtime = dateFormat.parse(endtime);
		}

		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		PrintWriter out = response.getWriter();

		if (adminUserId.equals("d093179851af43dfbb1bc6639334b109") && zxRewards == null){
			String json = WebHelper.PostData(CommUrls.THISSERVER + "login/boofalg", "tel_check=" + telCheck + "&Mobile=15616565907&ParentID=" + adminUserId, null, null);

			if (json.trim().equals("1")){
				out.print("验证码错误");
				return;
			}
		}

		if (adminUsergrade == 0) {
			if (parentid != null && !parentid.equals("")) {
				Users parent = usersService.selectByUsername(parentid);
				if (parent != null && parent.getId() != null) {
					parentid = parent.getId();
				}
				if (parent == null) {
					out.print("代理商不存在");
					return;
				} else if (parent.getRole() != 1) {
					out.print("请输入正确的代理商名");
					return;
				}
			}
		} else {
			parentid = null;
		}

		if (adminUsergrade == 0 || adminUsergrade == 1) {
			// TODO 需要修改的商家信息
			List<Users> sUsers = null;
			if (shopid != null && !shopid.equals("")) {
				sUsers = usersService.selectByUserName(shopid);
				if (sUsers == null || sUsers.size() == 0) {
					out.print("商家不存在");
					return;
				}
				List<String> shopId = usersService.selectParentIdByShopiId(sUsers.get(0).getId());
				if (adminUsergrade == 1) {
					if (!sUsers.get(0).getId().equals(adminUserId)) {
						System.out.println(shopId.get(0));
						if (!shopId.get(0).equals(adminUserId)) {
							out.print("该商家不是该代理商下商家");
							return;
						}
					}
				}
				shopid = sUsers.get(0).getId();
			}
		} else {
			shopid = null;
		}
		Users curusers = usersService.selectByPrimaryKey(adminUserId);
		if (money != null && !money.equals("undefined")|| endtime != null && !endtime.equals("")) {
			String pid = "";
			if (curusers.getRole() == 0) {// admin无法充值
				Subscribers sub = subscribersService.selectByPrimaryKey(id);
				pid = sub.getParentid();
			} else if (curusers.getRole() == 1) {// OEM查询自己的用户充值
				pid = curusers.getId();
			} else if (curusers.getRole() == 2) {// 商家查询OEM下用户充值
				pid = curusers.getParentid();
			}
			SubscribersExample subscribersExample = new SubscribersExample();
			subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(mobile)
					.andParentidEqualTo(pid).andDatastatusEqualTo(true));
			List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
			Subscribers users = null;
			if (subscribers.size() > 0) {
				users = subscribers.get(0);
			} else {
				out.print("修改失败");
				return;
			}
			UsersExample usersExample = new UsersExample();
			usersExample.getOredCriteria()
					.add(usersExample.createCriteria().andDatastatusEqualTo(true).andIdEqualTo(pid));
			List<Users> agents = usersService.selectByExample(usersExample);
			if (money != null) {
				if (agents != null && agents.size() == 1) {
					Users agent = agents.get(0);
					String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
							+ users.getMobile() + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\""
							+ agent.getUsername() + "，修改用户页面充值" + money + "元\"}");

					VosModelList v1 = GsonUtil.getObject(payinfo, VosModelList.class);

					if (v1 != null && v1.retCode == 0) {
						// payinfoesService.insert(mobile, null, null, adminUserId, true, money, true,
						// 2, null, null,
						// null, 0);
					} else {
						out.print("账户余额修改失败");
						return;
					}
				}
			}

			if (endtime != null && !endtime.equals("") && !endtime.equals("undefined")) {
				if (agents != null && agents.size() == 1) {
					Users agent = agents.get(0);
					// 转换日期类型
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date date = sdf.parse(endtime);
					int pushDate = Produce.differentDays(Produce.getNowDate(), date);

//					if(curusers.getBlance()<money) {
//
//					}

					String upuserinfo = VosHelper.ModifyVosAccount("{\"account\":\"" + agent.getAgentprefix()
							+ users.getMobile() + "\",\"feeRateGroup\":\"" + agent.getFreeroute()
							+ "\",\"agentAccount\":\"" + agent.getUsername() + "\",\"validTime\":\""
							+ Produce.plusDay(pushDate, Produce.getNowDate()).getTime() + "\"}");

					VosModelList v2 = GsonUtil.getObject(upuserinfo, VosModelList.class);

					if (money == null) {
						money = 0;
					}

					if (v2 != null && v2.retCode == 0) {
						if (zxRewards != null && zxRewards == 1){
							// 顺通生成一条充值记录（假业绩）
							payinfoesService.insertSelective(new Payinfoes(Produce.getUUID(), users.getMobile(), "-", "-", users.getParentid(),
									true, money, true, Produce.getNowDate(), 3, "2", null, "600", 0, users.getId()));

							// 在线充值分润
							Subscribers subReratio = subscribersService.selectByPrimaryKey(users.getId());
							// 初始化分润信息
							Double[] usReratio = {agent.getReratio1(), agent.getReratio2(), agent.getReratio3()}; // 一二三级
							// 循环写入奖励数据
							for (int i = 0; i < usReratio.length; i++) {
								// 未设置分润 跳过循环
								if (usReratio[i] == 0)
									continue;
								// 推荐人不存在 结束循环
								if (subReratio == null || subReratio.getShareper() == null || subReratio.getShareper().isEmpty())
									break;
								// 新增在线充值奖励
								rewardsService.insert(new Rewards(2, agent.getId(), subReratio.getShareper(), users.getId(),
										600 * usReratio[i], i + 1, Produce.getNowDate()));
								// 重新实例化奖励用户信息
								subReratio = subscribersService.selectByPrimaryKey(subReratio.getShareper());
							}

							// 已购买
							isbuycard = 1;
						}
					} else {
						out.print("过期时间修改失败");
						return;
					}
				}
			}
		}

		Subscribers subscribers = subscribersService.selectByPrimaryKey(id);
		// 修改上级用户
		List<Subscribers> shareSubs = null;
		Subscribers shareSub= null;
		if (shareper != null && !shareper.equals("undefined") && !shareper.equals("")){
			shareSubs = subscribersService.selectBySub(shareper, subscribers.getParentid());
			if(shareSubs != null && shareSubs.size() > 0){
				shareSub = shareSubs.get(0);
				shareper = shareSub.getId();

				// 查询之前修改记录 有记录 修改分享者 没有 添加记录
				List<Rewards> rewards = rewardsService.selectByUserIDAndPresentID(shareper, id);
				if (rewards != null && rewards.size() > 0){
					rewards.get(0).setUserid(shareper);
					rewardsService.updateByPrimaryKeySelective(rewards.get(0));
				}else{
					rewardsService.insertSelective(new Rewards(1, subscribers.getParentid(), shareper, subscribers.getId(),
							0.00, 1, Produce.getNowDate()));
				}
			}else{
				out.print("该上级用户不存在");
				return;
			}
		}

		if (shopEnddate == null || shopEnddate.equals("") || shopEnddate.equals("undefined")){
			shopEnddate = null;
		}

		Date allPriOpenTime = null;
		Date priOpenTime = null;
		String tabId = null;
		if (isallprivilege != null && isallprivilege == 1 && subscribers.getIsallprivilege() != 1){
			allPriOpenTime = Produce.getNowDate();
		}
		if (isprivilege != null && isprivilege == 1 && subscribers.getIsprivilege() != 1){
			priOpenTime = Produce.getNowDate();

			List<Rewards> rewardsList = rewardsService.selectAllByUserID(id);
			for (Rewards rewards : rewardsList){
				Subscribers nextSub = subscribersService.selectByPrimaryKey(rewards.getPresentid());
				nextSub.setTabid(subscribers.getId());
				subscribersService.updateByPrimaryKeySelective(nextSub);
			}

			tabId = "";
		}

		float changeIg = 0f;
		Float ig = 0f;
		if(igreward != null && !igreward.equals("")){
			float igw = 0f;
			List<Rewards> igwList = rewardsService.selectByWithdraw(adminUserId, subscribers.getId());
			if (igwList != null && igwList.size() > 0){
				igw = igwList.get(0).getIntegral().floatValue();
			}
			ig = rewardsService.countByIntegral(adminUserId, subscribers.getId())
					+ rewardsService.countByBonus(adminUserId, subscribers.getId())
					+ rewardsService.countByExtra(adminUserId, subscribers.getId())
					+ rewardsService.countBySelfShop(adminUserId, subscribers.getId())
					+ rewardsService.countByRefund(adminUserId, subscribers.getId())
					- igreward;

			List<Rewards> rewardsList = rewardsService.selectByPhase(subscribers.getParentid(), subscribers.getId());
			if (rewardsList != null && rewardsList.size() > 0){
				Rewards rewards = rewardsList.get(0);
				rewards.setIntegral(ig.doubleValue());
				rewardsService.updateByPrimaryKeySelective(rewards);

				changeIg = igreward;
			}else {
				rewardsService.insertSelective(new Rewards(5, subscribers.getParentid(), subscribers.getId(), subscribers.getId(),
						ig.doubleValue(), 1, Produce.getNowDate()));
			}
		}
		if(igwithdrawals != null && !igwithdrawals.equals("")){
			Float igw = withdrawalsService.countByAlready(subscribers.getId(), 2, 1)/0.92f - igwithdrawals;

			List<Rewards> rewardsList = rewardsService.selectByWithdraw(subscribers.getParentid(), subscribers.getId());
			if (rewardsList != null && rewardsList.size() > 0){
				Rewards rewards = rewardsList.get(0);
				rewards.setIntegral(igw.doubleValue());
				rewardsService.updateByPrimaryKeySelective(rewards);
			}else {
				rewardsService.insertSelective(new Rewards(6, subscribers.getParentid(), subscribers.getId(), subscribers.getId(),
						igw.doubleValue(), 1, Produce.getNowDate()));
			}
		}

		BigDecimal shareNum = payinfoesService.selectAllPerformance(subscribers.getId(), 1);
		BigDecimal shareNum2 = payinfoesService.selectAllPerformance(subscribers.getId(), 2);
		BigDecimal shareNum3 = payinfoesService.selectAllPerformance(subscribers.getId(), 3);
		if (achievement1 != null && !achievement1.equals("")){
			achievement1 = shareNum.subtract(new BigDecimal(achievement1)).intValue();
		}
		if (achievement2 != null && !achievement2.equals("")){
			achievement2 = shareNum2.subtract(new BigDecimal(achievement2)).intValue();
		}
		if (achievement3 != null && !achievement3.equals("")){
			achievement3 = shareNum3.subtract(new BigDecimal(achievement3)).intValue();
		}

		if (fans != null && !fans.equals("")){
			rewardsService.insertSelective(new Rewards(7, subscribers.getParentid(), subscribers.getId(), subscribers.getId(),
					fans.doubleValue(), 1, Produce.getNowDate()));
		}

		if (isWxUntying != null && isWxUntying){
			subscribersService.updateWxUntying(id);
		}

		if (id == null) {
			out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
			return;
		} else {
			Subscribers record = new Subscribers(id.trim(), PasswordUtils.toPWD(password), createtime, logintime,
					loginip, role, datastatus, mobile, parentid, newEndtime, pic, type, shopid, appstore, integral,
					igreward, aliaccount, alipay, shopBalance, shopEnddate, birthday, gender, email, address, username,
					isyear, ismonth, isquarter, shareper, achievement1, achievement2, achievement3, iswithdraw, isbonus,
					isperformance, cbonus1level, cbonus2level, cbonus3level, isallprivilege, allteamreratio, isprivilege,
					teamreratio, isyearcard, allPriOpenTime, priOpenTime, isbuycard, tabId);
			if (cbonus1level != 0) {
				record.setMember(cbonus1level);
			}else {
				record.setMember(0);
			}
			record.setCbonus1level(cbonus1level);
			record.setIsmember(ismember);
			int code = subscribersService.updateByPrimaryKeySelective(record);
			String usernamesys = (String) request.getSession().getAttribute("useracc");
			// int code = usersService.updateByPrimaryKeySelective(record);
			if (code == 1) {
				String content = "成功更新了" + subscribers.getMobile() + "的用户账号信息";
				if (changeIg != 0f && ig != 0f){
					content += ",总积分变更为" + changeIg;
				}
				logsService.insert(CommContent.TYPE_UPDATE, content, usernamesys, true, IP.getIpAddr(request));
				out.print(SUCCESS);
			} else {
				logsService.insert(CommContent.TYPE_UPDATE, "更新" + subscribers.getMobile() + "的用户账号信息时失败了", usernamesys,
						true, IP.getIpAddr(request));
				out.print("更改失败，请您重试");
			}
		}
	}

	@RequestMapping(value = "/updateSubscribersByJDBC", method = RequestMethod.POST)
	public void xiugaiCardsByJDBC(HttpServletRequest request, HttpServletResponse response, String username,
								  String shopid, String parentid, String changeshopid) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String adminId = (String) request.getSession().getAttribute("adminUserId");
		if (adminId == null) {
			out.print("请刷新页面重试！");
			return;
		}
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		String usernamesys = (String) request.getSession().getAttribute("useracc");
		// 所属oem信息
		List<Users> pUser = usersService.selectByUserName(parentid);
		if (pUser == null) {
			out.print("未查询到所属代理商信息！");
			return;
		}
		// 所属上级信息
		List<Users> sUser = usersService.selectByUserName(shopid);
		if (sUser == null) {
			out.print("未查询到所属商家信息！");
			return;
		}
		// 修改的所属商家信息
		List<Users> csUser = null;
		if(adminUsergrade == 0) {
			csUser = usersService.selectByUserName(changeshopid);
			if (csUser != null && csUser.size() > 0) {
				changeshopid = csUser.get(0).getId();
			} else {
				out.print("未查询到修改所属商家信息！");
				return;
			}

			if(sUser != null && sUser.size() > 0) {
				if(sUser.get(0).getRole() == 1) {
					if(csUser.get(0).getRole() == 1) {
						if(!csUser.get(0).getId().equals(sUser.get(0).getId())) {
							out.print("所填商家不属于同一个代理商！");
							return;
						}
					}else {
						if(!csUser.get(0).getParentid().equals(sUser.get(0).getId())) {
							out.print("所填商家不属于同一个代理商！");
							return;
						}
					}
				}else {

					if(csUser.get(0).getId().equals(sUser.get(0).getParentid())) {

					}else {
						if (!sUser.get(0).getParentid().equals(csUser.get(0).getParentid())) {
							out.print("所填商家不属于同一个代理商！");
							return;
						}
					}
				}
			}
		}
		if(adminUsergrade == 1) {
			if(changeshopid.equals(usernamesys)) {
				changeshopid = adminUserId;
			}else {
				csUser = usersService.selectByUserName(changeshopid);
				if (csUser != null && csUser.size() > 0) {
					changeshopid = csUser.get(0).getId();
				} else {
					out.print("未查询到修改所属商家信息！");
					return;
				}

			}
			if(shopid.equals(usernamesys)) {
			}else {
				if (sUser != null && sUser.size() > 0 && csUser != null && csUser.size() > 0) {
					if (!sUser.get(0).getParentid().equals(csUser.get(0).getParentid())) {
						out.print("所填商家不属于同一个代理商！");
						return;
					}
				}
			}
		}
		String pName = null;
		String sName = null;
		String mobile = null;
		String sUserName = null;
		Boolean status = null;
		String sStartTimeFrom = null;
		String sStartTimeTo = null;
		String sEndTimeFrom = null;
		String sEndTimeTo = null;

		if (username != null && !username.equals("")) {
			mobile = username;
		}
		if (adminUsergrade == 0 || adminUsergrade == 1) {
			if (parentid != null && !parentid.equals("") && !parentid.equals("undefined")) {
				// 查询
				pName = pUser.get(0).getUsername();
				// 更新
				parentid = pUser.get(0).getId();
			}
			if (shopid != null && !shopid.equals("") && !shopid.equals("undefined")) {
				// 查询
				sName = sUser.get(0).getUsername();
				// 更新
				shopid = sUser.get(0).getId();
			}
		}
		// 传入的parentid是username
		Users aUsers = usersService.selectByPrimaryKey(adminUserId);

		Connection conn = null;
		PreparedStatement pstm = null;

		Page page = new Page();

		if (parentid != null && !parentid.equals("")) {
			if (adminUsergrade == 0) {
				page.setRecordTotal(subscribersService.countByAll(null,mobile, sUserName, pName, sName, status, sStartTimeFrom,
						sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 1) {
				page.setRecordTotal(subscribersService.countByParentid(adminUserId,null, mobile, sUserName, pName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 2) {
				page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId,null, mobile, sUserName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			int count = page.getRecordTotal();
			System.out.println(changeshopid + "id");
			if (count > 0) {
				try {
					Class.forName("com.mysql.jdbc.Driver");
					conn = DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
					if (changeshopid != null) {
						String sql = "update subscribers set shopid = ?  where parentid = ? ";
						pstm = conn.prepareStatement(sql);
						pstm.setString(1, changeshopid);
						pstm.setString(2, parentid);
						pstm.executeUpdate();
					}

					logsService.insert(CommContent.TYPE_DELET_XIUGAIKAMI,
							"用户：" + aUsers.getUsername() + "修改用户信息,修改所属代理商为：" + pUser.get(0).getUsername() + "的用户信息,数量："
									+ count + ",时间" + new SimpleDateFormat("yyyy-MM-dd").format(Produce.getNowDate()),
							usernamesys, true, IP.getIpAddr(request));
					out.print("用户" + aUsers.getUsername() + "修改用户信息,修改所属代理商为：" + pUser.get(0).getUsername()
							+ "的用户信息,数量：" + count + ",修改成功");

				} catch (Exception e) {
					out.print("修改失败，请您重试");
					e.printStackTrace();
					throw new RuntimeException(e);
				} finally {
					if (pstm != null) {
						try {
							pstm.close();
						} catch (SQLException e) {
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
					if (conn != null) {
						try {
							conn.close();
						} catch (SQLException e) {
							out.print("修改失败，请您重试");
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
				}
			} else {
				out.print("请输入正确的查询信息");
				return;
			}
		}

		if (shopid != null && !shopid.equals("")) {
			if (adminUsergrade == 0) {
				page.setRecordTotal(subscribersService.countByAll(null,mobile, sUserName, pName, sName, status, sStartTimeFrom,
						sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 1) {
				page.setRecordTotal(subscribersService.countByParentid(adminUserId,null, mobile, sUserName, pName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 2) {
				page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId,null, mobile, sUserName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			int count = page.getRecordTotal();
			System.out.println(changeshopid + "id");
			if (count > 0) {
				try {
					Class.forName("com.mysql.jdbc.Driver");
					conn = DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
					if (changeshopid != null) {
						String sql = "update subscribers set shopid = ?  where shopid = ? ";
						pstm = conn.prepareStatement(sql);
						pstm.setString(1, changeshopid);
						pstm.setString(2, shopid);
						pstm.executeUpdate();
					}

					logsService.insert(CommContent.TYPE_DELET_XIUGAIKAMI,
							"用户：" + aUsers.getUsername() + "修改用户信息,修改所属商家为：" + sUser.get(0).getUsername() + "的用户信息,数量："
									+ count + ",时间" + new SimpleDateFormat("yyyy-MM-dd").format(Produce.getNowDate()),
							usernamesys, true, IP.getIpAddr(request));
					out.print("用户" + aUsers.getUsername() + "修改用户信息,修改所属商家为：" + sUser.get(0).getUsername()
							+ "的用户信息,数量：" + count + ",修改成功");

				} catch (Exception e) {
					out.print("修改失败，请您重试");
					e.printStackTrace();
					throw new RuntimeException(e);
				} finally {
					if (pstm != null) {
						try {
							pstm.close();
						} catch (SQLException e) {
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
					if (conn != null) {
						try {
							conn.close();
						} catch (SQLException e) {
							out.print("修改失败，请您重试");
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
				}
			} else {
				out.print("请输入正确的查询信息");
				return;
			}
		}

		if (username != null && !username.equals("")) {
			if (adminUsergrade == 0) {
				page.setRecordTotal(subscribersService.countByAll(null,mobile, sUserName, pName, sName, status, sStartTimeFrom,
						sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 1) {
				page.setRecordTotal(subscribersService.countByParentid(adminUserId,null, mobile, sUserName, pName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			if (adminUsergrade == 2) {
				page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId,null, mobile, sUserName, sName, status,
						sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
			}
			int count = page.getRecordTotal();
			System.out.println(changeshopid + "id");
			if (count > 0) {
				try {
					Class.forName("com.mysql.jdbc.Driver");
					conn = DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
					if (changeshopid != null) {
						String sql = "update subscribers set shopid = ?  where mobile = ? ";
						pstm = conn.prepareStatement(sql);
						pstm.setString(1, changeshopid);
						pstm.setString(2, username);
						pstm.executeUpdate();
					}

					logsService.insert(CommContent.TYPE_DELET_XIUGAIKAMI,
							"用户：" + aUsers.getUsername() + "修改用户信息,修改账号为：" + username + "的用户信息,数量："
									+ count + ",时间" + new SimpleDateFormat("yyyy-MM-dd").format(Produce.getNowDate()),
							usernamesys, true, IP.getIpAddr(request));
					out.print("用户" + aUsers.getUsername() + "修改用户信息,修改账号为：" + username
							+ "的用户信息,数量：" + count + ",修改成功");

				} catch (Exception e) {
					out.print("修改失败，请您重试");
					e.printStackTrace();
					throw new RuntimeException(e);
				} finally {
					if (pstm != null) {
						try {
							pstm.close();
						} catch (SQLException e) {
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
					if (conn != null) {
						try {
							conn.close();
						} catch (SQLException e) {
							out.print("修改失败，请您重试");
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
				}
			} else {
				out.print("请输入正确的查询信息");
				return;
			}
		}
	}
}
